import 'package:flutter/material.dart';
import 'package:flutter_demo/controllers/user_controller.dart';
import 'package:flutter_demo/utils/const.dart';
import 'package:get/get.dart';

class LoginPage extends GetView<UserController> {
  LoginPage({Key? key}) : super(key: key);

  final _formLoginKey = GlobalKey<FormState>();
  final _formRegisterKey = GlobalKey<FormState>();

  final _loginFormData = <String, String?>{};
  final _registerFormData = <String, String?>{};

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("登录"),
        elevation: 0,
        toolbarHeight: Const.kAppBarHeight,
      ),
      body: DefaultTabController(
        length: 2,
        child: Column(
          children: [
            TabBar(
              padding: EdgeInsets.zero,
              indicatorSize: TabBarIndicatorSize.label,
              indicatorWeight: 3,
              labelStyle: const TextStyle(fontSize: 18),
              labelColor: Get.theme.primaryColor,
              tabs: const [Tab(text: "登录"), Tab(text: "注册")],
              unselectedLabelStyle: const TextStyle(fontSize: 15),
            ),
            const Divider(
              height: 0.5,
            ),
            Expanded(
              child: TabBarView(
                children: [_buildLoginView(), _buildRegisterView()],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLoginView() {
    return Form(
      key: _formLoginKey,
      child: ListView(
        children: [
          TextFormField(
            keyboardType: TextInputType.emailAddress,
            decoration: const InputDecoration(
              icon: Icon(Icons.email),
              labelText: '用户名或邮箱',
            ),
            validator: (value) {
              if (value?.isEmpty == true) {
                return "用户名或邮箱不能为空";
              }
            },
            onSaved: (value) {
              _loginFormData["username"] = value;
            },
          ),
          TextFormField(
            decoration: const InputDecoration(
              icon: Icon(Icons.password_outlined),
              labelText: '密码',
            ),
            validator: (value) {
              if (GetUtils.isNullOrBlank(value) == true) {
                return "密码不能为空";
              }
            },
            onSaved: (value) {
              _loginFormData["pwd"] = value;
            },
          ).paddingOnly(top: 20),
          ElevatedButton(
            onPressed: _handleLogin,
            child: const Text("登录"),
          ).paddingOnly(top: 20),
        ],
      ),
    ).paddingAll(20);
  }

  Widget _buildRegisterView() {
    return Form(
      key: _formRegisterKey,
      child: ListView(
        children: [
          TextFormField(
            decoration: const InputDecoration(
              icon: Icon(Icons.verified_user),
              labelText: '输入英文用户名',
              isDense: true,
            ),
            validator: (value) {
              if (GetUtils.isNullOrBlank(value) == true) {
                return "用户名不能为空";
              }
              return null;
            },
            onSaved: (value) {
              _registerFormData["username"] = value;
            },
          ),
          TextFormField(
            keyboardType: TextInputType.emailAddress,
            decoration: const InputDecoration(
              icon: Icon(Icons.email),
              labelText: '邮箱',
              hintText: "绑定邮箱",
              isDense: true,
            ),
            validator: (value) {
              if (GetUtils.isNullOrBlank(value) == true) {
                return "邮箱不能为空";
              }
              if (!GetUtils.isEmail(value.toString())) {
                return "邮箱格式不正确";
              }
              return null;
            },
            onChanged: (value) {
              _registerFormData["email"] = value;
            },
          ).paddingOnly(top: 20),
          TextFormField(
            decoration: const InputDecoration(
              icon: Icon(Icons.password_outlined),
              labelText: '密码',
              hintText: "密码最小长度为6",
              isDense: true,
            ),
            validator: (value) {
              if (GetUtils.isNullOrBlank(value) == true) {
                return "密码不能为空";
              }
              if (value!.length < 6) {
                return "密码最小长度为6";
              }
              return null;
            },
            onChanged: (value) {
              _registerFormData["pwd"] = value;
            },
          ).paddingOnly(top: 20),
          TextFormField(
            decoration: const InputDecoration(
              icon: Icon(Icons.confirmation_number),
              labelText: '再次输入密码',
              isDense: true,
            ),
            validator: (value) {
              if (GetUtils.isNullOrBlank(value) == true) {
                return "密码不能为空";
              }
              if (value != _registerFormData["pwd"]) {
                return "两次输入的密码不一致";
              }
              return null;
            },
            onSaved: (value) {
              _registerFormData["re_pwd"] = value;
            },
          ).paddingOnly(top: 20),
          TextFormField(
            decoration: InputDecoration(
              icon: const Icon(Icons.confirmation_num),
              labelText: '邮箱验证码',
              isDense: true,
              suffix: GestureDetector(
                onTap: _sendCode,
                child: const Text("发送"),
              ),
            ),
            validator: (value) {
              if (GetUtils.isNullOrBlank(value) == true) {
                return "验证码不能为空";
              }
              return null;
            },
            onSaved: (value) {
              _registerFormData["code"] = value;
            },
          ).paddingOnly(top: 20),
          ElevatedButton(
            onPressed: _handleRegister,
            child: const Text("注册"),
          ).paddingOnly(top: 20),
        ],
      ),
    ).paddingAll(20);
  }

  _handleLogin() async {
    if (_formLoginKey.currentState?.validate() == true) {
      _formLoginKey.currentState?.save();
      var resp = await controller.login(_loginFormData["username"]!, _loginFormData["pwd"]!);
      if (resp.status == "0") {
        Get.snackbar("提示", "登录失败,${resp.msg}", backgroundColor: Colors.yellowAccent);
      }
    }
  }

  _handleRegister() async {
    if (_formRegisterKey.currentState?.validate() == true) {
      _formRegisterKey.currentState?.save();
      var resp = await controller.register(_registerFormData);
      if (resp.status == "0") {
        Get.snackbar("提示", "注册失败,${resp.msg}", backgroundColor: Colors.yellowAccent);
      }
    }
  }

  _sendCode() async {
    var resp = await controller.sendCode(_registerFormData["email"]!);
    if (resp.status == "0") {
      Get.snackbar("提示", "${resp.msg}", backgroundColor: Colors.yellowAccent);
    }
  }
}
